package com.powerunion.datacollection.service;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.dao.TransmitTaskDao;
import com.powerunion.datacollection.model.ApproveWorkItem;
import com.powerunion.datacollection.model.SubmissionWorkItem;
import com.powerunion.datacollection.model.TransmitTask;

import com.powerunion.util.log.LogHelper;

public class TransmitTaskManager {
	private static Logger logger = LogHelper.getInstance().getLogger(
			TransmitTaskManager.class);
	private TransmitTaskDao dao = null;

	public TransmitTaskManager() {
		super();
		this.dao = (TransmitTaskDao) DaoFactory.getInstance().getDao(
				TransmitTaskDao.class);
	}

	public boolean save(String saveStr, String transmitUser)
			throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(saveStr)) {
			String[] args = { "saveStr" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter saveStr NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		// 参数为空
		if (StringUtils.isEmpty(transmitUser)) {
			String[] args = { "transmitUser" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter transmitUser NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		JSONObject jsonObject = JSONObject.fromObject(saveStr);
		TransmitTask transmitTask = (TransmitTask) JSONObject.toBean(
				jsonObject, TransmitTask.class);
		transmitTask.setTransmitUser(transmitUser);
		boolean flag = false;
		flag = this.dao.save(transmitTask);

		if (flag) {
			int taskType = transmitTask.getTaskType();
			String receiveUsers = transmitTask.getReceiveUsers();
			if (taskType == Constants.TASK_TYPE_APPROVEWORK) {//审批任务
				ApproveWorkItemManager awm = new ApproveWorkItemManager();
				ApproveWorkItem awi = awm.getByKey(transmitTask.getTaskId());
				//隐藏当前转发人的审批任务
				awm.update4User(Constants.APPROVE_HIDE, transmitTask.getTaskId());
				flag = awm.saveByTransmit(awi, receiveUsers);
			} else if (taskType == Constants.TASK_TYPE_SUBMISSIONWORK) {//采集任务
				SubmissionWorkItemManager swm = new SubmissionWorkItemManager();
				SubmissionWorkItem swi = swm.getByKey(transmitTask.getTaskId());
				//隐藏当前转发人的采集任务
				swm.updateState4User(Constants.SUBMISSION_HIDE, transmitTask.getTaskId());
				flag = swm.saveByTransmit(swi, receiveUsers);
			}
		}

		return flag;
	}

}
